/**
 * Copyright (C)  2011  chen wei hua.
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 2.0
 * or any later version published by the Free Software Foundation;
 * with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
 * A copy of the license is included in the section entitled "GNU Free Documentation License".
 */
package com.javaeye.order.dao;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.javaeye.common.dto.DTO;
import com.javaeye.order.dto.Product;
import com.javaeye.common.web.PageInfo;

public class ProductDAOHibernate extends HibernateDaoSupport implements ProductDAO {
	
	@SuppressWarnings("unchecked")
	public List<Product> getAutoCompleteProducts(String name, final int size) {
		name = name.trim();
		final String sql = " from Product p where p.name like '%" 
			+ name +"%' or p.type like '%" + name + "%' or p.productNo like '%" 
		+ name + "%' or p.customerNo like '%" + name + "%'";
		HibernateCallback action = new HibernateCallback() {
			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(sql);
				query.setFirstResult(0);
				query.setMaxResults(size);
				return query.list();
			}
		};
		return getHibernateTemplate().executeFind(action);
	}
	
	@SuppressWarnings("unchecked")
	public long getProductCountByCategoryId(int categoryId) {
		String sql = "select count(p.id) from Product p where p.category=?";
		List result = getHibernateTemplate().find(sql, String.valueOf(categoryId));
		long count = 0;
		if (result.size() > 0) {
			count = (Long)result.get(0);
		}
		return count;
	}
	
	@SuppressWarnings("unchecked")
	public List getPageData(final DTO contidions, final PageInfo pageInfo) {
		HibernateCallback action = new HibernateCallback() {
			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				
				int pageIndex = pageInfo.getPageIndex();
				int pageSize = pageInfo.getPageSize();
				Product product = (Product)contidions;
				Criteria crit = session.createCriteria(Product.class);
				if (!"".equals(product.getName().trim())) {
					crit.add(Restrictions.or(Restrictions.or(
									Restrictions.like("name", "%" + product.getName().trim() + "%")
									, Restrictions.like("productNo", "%" + product.getName().trim() + "%"))
									, Restrictions.like("customerNo", "%" + product.getName().trim() + "%")));
				}
				if (!"-1".equals(product.getCategory().trim())) {
					crit.add(Restrictions.eq("category", product.getCategory().trim()));
				}
				crit.setProjection(Projections.rowCount());
				Integer rowNumber = (Integer)crit.uniqueResult();
				pageInfo.setCount(rowNumber);
				
				crit.setProjection(null);//取得了总数后,为了能够再次取得对象列表
				crit.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);//当hibernate采用关联的时候不使用这个返回的是个对象数组，加上这个返回的是当前列表的对象。
				crit.setFirstResult(pageIndex * pageSize);
				crit.setMaxResults(pageSize);
				return crit.list();
			}
		};
		return getHibernateTemplate().executeFind(action);
	}
	
	@SuppressWarnings("unchecked")
	public boolean isExistProduct(final Product product) {
		String productNo = product.getProductNo().trim();
		if ("".equals(productNo)) {
			final String sql = " from Product p where category=? and p.name=? and p.type=? and p.customerNo=?";
			List result = getHibernateTemplate().find(sql, new Object[]{
					product.getCategory(), product.getName(), product.getType(), product.getCustomerNo()
			});
			if (result != null && result.size() > 0) {
				return true;
			}
		} else {
			final String sql = " from Product p where p.productNo =?";
			List result = getHibernateTemplate().find(sql, productNo);
			if (result != null && result.size() > 0) {
				return true;
			}
		}
		return false;
		
	}
	
	@Override
	public void saveProduct(Product product) {
		getHibernateTemplate().saveOrUpdate(product);
		logger.debug("Product id set to: " + product.getId());
	}

	@Override
	public Product getProduct(int id) {
		return (Product)getHibernateTemplate().get(Product.class, id);
	}

	@Override
	public void removeProduct(int id) {
		Object o = getHibernateTemplate().load(Product.class, id);
		getHibernateTemplate().delete(o);
	}

}
